package com.qingmu.club.minaapi.controller.member;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qingmu.club.minaapi.custom.logic.UsersWxLogic;
import com.qingmu.club.minaapi.plus.entity.*;
import com.qingmu.club.minaapi.plus.service.*;
import com.qingmu.club.minaapi.utils.ConvertUtil;
import com.qingmu.club.minaapi.utils.ResponseObject;
import com.qingmu.club.minaapi.utils.Utils;
import com.qingmu.club.minaapi.wechat.QrCodeUtil;
import com.qingmu.club.minaapi.wechat.WechatUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@CrossOrigin(origins = "*", methods = {RequestMethod.POST, RequestMethod.GET})
@Api(value = "积分商城相关(会员端小程序)", description = "积分商城相关(会员端小程序)")
@RequestMapping("/member/integralMall")
public class MemberIntegralMallController {

    @Autowired
    ClubUsersService clubUsersService;

    @Autowired
    ClubUsersIntegralService clubUsersIntegralService;

    @Autowired
    UsersService usersService;

    @Autowired
    IntegralGoodsService integralGoodsService;

    @Autowired
    OrderInfoService orderInfoService;

    @Autowired
    UsersWxLogic usersWxLogic;

    @Value("${web.upload-path}")
    private String uploadPath;
    @Value("${web.imageService}")
    private String wanPath;


    @RequestMapping(value = "/getIntegralGoods", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查询累计积分、积分商品列表")
    public ResponseEntity getIntegralGoods(
            @ApiParam(required = true, value = "门店id") @RequestParam(required = true) String shopId,
            @ApiParam(required = true, value = "会员id") @RequestParam(required = true) String userId

    ) {
        Users users = this.usersService.getById(userId);
        if(users == null){
            return ResponseObject.error(401,"作者信息找不到");
        }
        Integer jf = 0;
        Integer time = 0;
//        if (userId != null) {
            QueryWrapper<ClubUsers> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq(ClubUsers.USER_ID, userId).eq(ClubUsers.SHOP_ID, shopId);
            ClubUsers clubUsers = this.clubUsersService.getOne(queryWrapper1);
//            if (clubUsers == null){
//                return ResponseObject.error(556,"用户信息有误");
//            }

            QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(OrderInfo.USER_ID, userId).eq(OrderInfo.STATUS, 1);
            List<OrderInfo> orderInfoList = this.orderInfoService.list(queryWrapper);
            if (!CollectionUtils.isEmpty(orderInfoList)) {
                time = orderInfoList.size();
            }
//        if(clubUsers==null){
//            return ResponseObject.error(556,"用户未关注门店");
//        }
        if (clubUsers != null) {
            jf = clubUsers.getUserJf()==null?0:clubUsers.getUserJf();
        }
//        }

        QueryWrapper<IntegralGoods> qw = new QueryWrapper<>();
        qw.eq(IntegralGoods.SHOP_ID,shopId);
        qw.eq(IntegralGoods.STATUS,1); //上架
        List<IntegralGoods> integralGoodsList  = this.integralGoodsService.list(qw);
//        if(CollectionUtils.isEmpty(integralGoodsList)){
//            return null;
//        }
//        int[] src = {orderInfoList.size()};
//        List<Integer> timeList = Arrays.stream( src ).boxed().collect(Collectors.toList());

//        QueryWrapper<ClubUsers> clubUsersQueryWrapper = new QueryWrapper<>();
//        clubUsersQueryWrapper.lambda().eq(ClubUsers::getId, clubUsersId);
//        List<ClubUsers> userJfList = this.clubUsersService.list(clubUsersQueryWrapper);

        HashMap<String,Object> map = new HashMap<>();
        map.put("integralGoodsList",integralGoodsList);
        map.put("userJf",jf);
        map.put("time",time);

        return ResponseObject.success(map);

    }

    @RequestMapping(value = "/getIntegralLog", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查看积分明细(查看明细)")
    public ResponseEntity getIntegralLog(
//            @ApiParam(required = true, value = "用户积分表会员id") @RequestParam(required = true) String clubUsersId
            @ApiParam(required = true, value = "门店id") @RequestParam(required = true) String shopId,
            @ApiParam(required = true, value = "会员id") @RequestParam(required = true) String userId

    ) {
        Users users = this.usersService.getById(userId);
        if(users == null){
            return ResponseObject.error(401,"作者信息找不到");
        }
        QueryWrapper<ClubUsersIntegral> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ClubUsersIntegral.USER_ID, userId)
                .eq(ClubUsersIntegral.SHOP_ID, shopId)
                .orderByDesc(ClubUsersIntegral.CREATE_TIME);
        List<ClubUsersIntegral> clubUsersIntegralList = this.clubUsersIntegralService.list(queryWrapper);

        return  ResponseObject.success(clubUsersIntegralList);
    }


    @RequestMapping(value = "/exchangeNow", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "立即兑换积分生成二维码")
    public ResponseEntity exchangeNow(
            @ApiParam(required = true, value = "会员id") @RequestParam(required = true) String userId,
            @ApiParam(required = true, value = "门店id") @RequestParam(required = true) String shopId,
            @ApiParam(required = true, value = "积分商品id") @RequestParam(required = true) String goodsId


    ) {
        Users users = this.usersService.getById(userId);
        if(users == null){
            return ResponseObject.error(401,"会员信息找不到");
        }
        QueryWrapper<ClubUsers> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq(ClubUsers.USER_ID, userId)
                .eq(ClubUsers.SHOP_ID,shopId);
        ClubUsers clubUsers = this.clubUsersService.getOne(queryWrapper1);
        if(clubUsers==null){
            return ResponseObject.error(556,"积分数量不够");
        }

        IntegralGoods integralGoods = this.integralGoodsService.getById(goodsId);
        if (integralGoods == null) {
            return ResponseObject.error(601,"积分商品不存在");
        }

        if (clubUsers.getUserJf() < integralGoods.getGoodsPrice()){
            return ResponseObject.error(555,"积分数量不够，请兑换其它商品");
        }
        int type = 0;
//        Long codeId = new Date().getTime();
        String goodsCode = QrCodeUtil.createQrcode(uploadPath, "userId="+userId+",shopId="+shopId+",type="+type+",goodsId="+goodsId+",codeId="+ UUID.randomUUID().toString().replace("-",""));//生成积分商品二维码
        if (StringUtils.isEmpty(goodsCode)) {
            return ResponseObject.error(556, "二维码生成失败");
        }

//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        clubUsers.setApplyTime(new Date());
        boolean state = this.clubUsersService.updateById(clubUsers);
        if (!state) {
            return ResponseObject.error();
        }

        HashMap<String,Object> map =  new HashMap<>();
        map.put("goodsCodeUrl",wanPath+goodsCode);

        return ResponseObject.success(map);

    }

    @RequestMapping(value = "/testCreateQrCode", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "测试二维码")
    public ResponseEntity testCreateQrCode(

    ) {
        String goodsCode = QrCodeUtil.createQrcode(uploadPath, "orderId=123456");//生成积分商品二维码
        if (StringUtils.isEmpty(goodsCode)) {
            return ResponseObject.error(556, "二维码生成失败");
        }
        HashMap<String,Object> map =  new HashMap<>();
        map.put("goodsCode",goodsCode);
        return ResponseObject.success(map);
    }

    @RequestMapping(value = "/getGoodsDetails", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查询商品详情")
    public ResponseEntity getGoodsDetails(
            @ApiParam(required = true, value = "积分商城商品id") @RequestParam(required = true) String goodsId,
            @ApiParam(required = true, value = "用户id") @RequestParam(required = true) String userId

    ) {
        Users users = this.usersService.getById(userId);
        if(users == null){
            return ResponseObject.error(401,"作者信息找不到");
        }
        IntegralGoods integralGoods = this.integralGoodsService.getById(goodsId);

        if (integralGoods == null) {
            return ResponseObject.error(601,"积分商品不存在");
        }

        boolean isExchange = true;

        QueryWrapper<ClubUsers> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq(ClubUsers.USER_ID, userId).eq(ClubUsers.SHOP_ID, integralGoods.getShopId());
        ClubUsers clubUsers = this.clubUsersService.getOne(queryWrapper1);
        if(clubUsers==null){
            isExchange=false;
        }else {
            if (clubUsers.getUserJf() < integralGoods.getGoodsPrice()) {
                isExchange=false;
            }
        }

        Map<String,Object> map = new HashMap<>();
        map.put("isExchange",isExchange);
        map.put("integralGoods",integralGoods);

        return ResponseObject.success(map);
    }


    @RequestMapping(value = "/getOrderInfo", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查询兑换订单信息(兑换记录)")
    public ResponseEntity getOrderInfo(
            @ApiParam(required = true, value = "会员id") @RequestParam(required = true) String userId,
            @ApiParam(required = true, value = "门店id") @RequestParam(required = true) String shopId

            ) {
        Users users = this.usersService.getById(userId);
        if(users == null){
            return ResponseObject.error(401,"作者信息找不到");
        }
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OrderInfo.USER_ID, userId)
                .eq(OrderInfo.SHOP_ID, shopId)
                .orderByDesc(OrderInfo.CREATE_TIME)//订单按照时间排序
                .eq(OrderInfo.STATUS,1);
        List<OrderInfo> orderInfoList = this.orderInfoService.list(queryWrapper);

        return  ResponseObject.success(orderInfoList);
    }

}
